import React, { useRef, useState, useEffect } from 'react';

import { v4 as uuid4 } from 'uuid';
// styles
import styles from './index.less';
// 自定义组件
// 自定义工具和方法

export default () => {
  const [polylineArr, setPolylineArr] = useState([
    {
      name: '123123',
      positions: [
        [39.9042, 116.4074], // 北京, 中国
        [39.3434, 117.3616], // 天津, 中国
        [36.0671, 120.3826], // 青岛, 中国
        [31.2304, 121.4737], // 上海, 中国
        [30.2741, 120.1551], // 杭州, 中国
      ],
      color: '#6bffff',
    },
  ]);

  /**
   * @desc 绘制点位数据
   * @param {*} data
   * @returns
   */
  const transData = (data) => {
    let returnData = [];
    if (data && Array.isArray(data) && data.length) {
      let returnItem = null;
      data.map((item) => {
        returnItem = {
          positions: item.positions,
          id: item.id || uuid4(),
          overlayType: 'EditPolyline',
          style: {
            color: item.color || '#6bffff',
            weight: 1,
            opacity: 1,
            fillOpacity: 0.5,
            fillColor: '#6bffff',
            fillOpacity: 1,
          },
          label: item.name,
          // 标注样式
          labelStyle: {
            color: item.color || '#6bffff',
            fontSize: '14px',
            fontWeight: 'bold',
          },
          payload: {
            ...item,
          },
        };
        returnData.push(returnItem);
      });
    }
    return returnData;
  };

  // 清除图层
  const clearFun = () => {
    window?.LFTViewer?.setLFTAllData(
      [
        {
          type: 'ctrl',
          payload: [
            {
              ctrl: 'clearLayer',
              groupId: 'MapGroup',
              layerId: 'polylineLayer',
            },
          ],
        },
      ],
      () => {
        // console.log('清除完成了');?
      },
    );
  };
  // 绘制图层
  const drawFun = () => {
    let drawData = transData(polylineArr);
    console.log('drawData', drawData);
    window?.LFTViewer?.setLFTAllData(
      [
        {
          type: 'draw',
          payload: [
            {
              groupId: 'MapGroup',
              layerId: 'polylineLayer',
              payload: drawData,
            },
          ],
        },
      ],
      () => {
        // console.log('绘制完成了');
      },
    );
  };
  useEffect(() => {
    // console.log('viewer', window.LFTViewer);
    window?.LFTViewer?.setLFTAllData(
      [
        {
          type: 'ctrl',
          payload: [
            {
              ctrl: 'createLayer',
              groupId: 'MapGroup',
              layerId: 'polylineLayer',
            },
          ],
        },
      ],
      () => {
        // console.log('创建完成了');
        drawFun();
      },
    );
    return () => {
      clearFun();
    };
  }, []);
  return <></>;
};
